/*
 * FtpTest.cpp
 *
 *  Created on: 2012-12-26
 *      Author: yangentao@gmail.com
 */

#include <iostream>
#include "FtpTest.h"
#include "TaskQueue.h"
#include "../yet/net/SocketMonitor.h"
#include "../yet/WinLoop.h"

namespace ftp {
using namespace yet;

bool open(FtpContext& c, string host, u_short port, string user, string password) {
	TaskQueue loginQueue(&c, taskAND);
	loginQueue.appendTask()->connect(host, port);
	loginQueue.appendTask()->login(user, password);
	loginQueue.appendTask()->help();
	loginQueue.appendTask()->syst();
	loginQueue.appendTask()->type("A");
	loginQueue.appendTask()->feat();
	loginQueue.appendTask()->pwd();
	return loginQueue.execute();
}
bool rein(FtpContext& c) {
	TaskQueue loginQueue(&c, taskAND);
	loginQueue.appendTask()->rein();
	loginQueue.appendTask()->login(c.username, c.password);
	return loginQueue.execute();
}


bool download(FtpContext& c, string remoteFile, string localpath) {
	TaskQueue downloadQueue(&c, taskAND);
	downloadQueue.appendTask()->type("I");
	downloadQueue.appendTask()->pasv();
	downloadQueue.appendTask()->retr(remoteFile, localpath);
	return downloadQueue.execute();
}
bool downloadRest(FtpContext& c, int offset, string remoteFile, string localpath) {
	TaskQueue downloadQueue(&c, taskAND);
	downloadQueue.appendTask()->type("I");
	downloadQueue.appendTask()->pasv();
	downloadQueue.appendTask()->rest(offset);
	downloadQueue.appendTask()->retr(remoteFile, localpath);
	return downloadQueue.execute();
}
bool upload(FtpContext& c, string localpath, string remoteFile) {
	TaskQueue uploadQueue(&c, taskAND);
	uploadQueue.appendTask()->type("I");
	uploadQueue.appendTask()->pasv();
	uploadQueue.appendTask()->stor(localpath, remoteFile);
	return uploadQueue.execute();
}
bool upload(FtpContext& c, string localpath) {
	TaskQueue uploadQueue(&c, taskAND);
	uploadQueue.appendTask()->type("I");
	uploadQueue.appendTask()->pasv();
	uploadQueue.appendTask()->stou(localpath);
	return uploadQueue.execute();
}
bool append(FtpContext& c, string localpath, string remoteFile) {
	TaskQueue uploadQueue(&c, taskAND);
	uploadQueue.appendTask()->type("I");
	uploadQueue.appendTask()->pasv();
	uploadQueue.appendTask()->appe(localpath, remoteFile);
	return uploadQueue.execute();
}
bool list(FtpContext& c, string remotepath){
	TaskQueue q(&c, taskAND);
	q.appendTask()->type("A");
	q.appendTask()->pasv();
	q.appendTask()->list(remotepath);
	return q.execute();
}
bool nlst(FtpContext& c, string remotepath){
	TaskQueue q(&c, taskAND);
	q.appendTask()->type("A");
	q.appendTask()->pasv();
	q.appendTask()->nlst(remotepath);
	return q.execute();
}

void ftptest() {
	FtpContext c;
	if (!open(c, "127.0.0.1", 21, "yet", "19810218")) {
		return;
	}

	Task siteTask(&c);
	siteTask.site("HELP").execute();

	Task quitTask(&c);
	quitTask.quit().execute();
}

} /* namespace yet */
